<template>
  <div class="app-container" v-loading="loading">
    <div class="card-header">
      <div class="header-title">
        <span>{{ planInfo.planCode }}</span>
      </div>
      <div class="creator-info">
        <span>创建人：{{ planInfo.creator }}</span>
        <span>创建时间：{{ planInfo.createTime }}</span>
      </div>
      <div class="status-tag">
        <span class="tag-wrapper" :class="'status-' + statusInfo.type">{{ statusInfo.text }}</span>
      </div>
    </div>

    <div class="action-bar">
      <el-button size="small" type="primary" plain @click="handleEdit">编辑</el-button>
      <el-button size="small" type="danger" plain @click="handleDelete">删除</el-button>
      <el-button size="small" type="primary" plain @click="handleSplit" :disabled="planInfo.status !== '0'">分解</el-button>
      <el-button size="small" type="primary" plain @click="handlePrint">打印</el-button>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="基础信息" name="baseInfo">
        <el-descriptions :column="2" border>
        <el-descriptions-item label="计划编号">{{ planInfo.planCode }}</el-descriptions-item>
        <el-descriptions-item label="计划名称">{{ planInfo.planName }}</el-descriptions-item>
        <el-descriptions-item label="来源类型">{{ planInfo.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="生产订单编号">{{ planInfo.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="成品名称">{{ planInfo.productName }}</el-descriptions-item>
          <el-descriptions-item label="成品编号">{{ planInfo.productCode }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ planInfo.specification }}</el-descriptions-item>
          <el-descriptions-item label="产品类型">
            <dict-tag :options="dict.type.product_type" :value="planInfo.productType"/>
        </el-descriptions-item>
          <el-descriptions-item label="单位">{{ planInfo.unit }}</el-descriptions-item>
          <el-descriptions-item label="计划数量">{{ planInfo.plannedQty }}</el-descriptions-item>
        <el-descriptions-item label="计划开工时间">{{ planInfo.planStartTime }}</el-descriptions-item>
        <el-descriptions-item label="计划完工时间">{{ planInfo.planEndTime }}</el-descriptions-item>
        <el-descriptions-item label="需求日期">{{ planInfo.requiredDate }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ planInfo.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item label="附件">
            <el-button type="text" v-if="planInfo.attachment">下载附件</el-button>
            <span v-else>无</span>
          </el-descriptions-item>
      </el-descriptions>
      </el-tab-pane>
      
      <el-tab-pane label="生产工单" name="productionOrder">
        <div class="table-toolbar">
          <el-button size="small" type="primary" plain icon="el-icon-download">导出</el-button>
      </div>
      <el-table :data="workOrderList" style="width: 100%">
          <el-table-column type="selection" width="55" align="center" fixed="left" />
          <el-table-column label="序号" type="index" width="55" align="center" fixed="left" />
          <el-table-column label="工单编号" prop="workOrderCode" align="center" width="150" fixed="left" />
          <el-table-column label="工单名称" prop="workOrderName" align="center" width="150" fixed="left" />
          <el-table-column label="工单进度" prop="progress" align="center" width="150" fixed="left">
            <template slot-scope="scope">
              <el-progress :percentage="scope.row.progressValue" :color="scope.row.progressColor"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="关联计划" prop="relatedPlan" align="center" width="120" />
          <el-table-column label="产品名称" prop="productName" align="center" width="120" />
          <el-table-column label="产品编码" prop="productCode" align="center" width="120" />
          <el-table-column label="规格型号" prop="specifications" align="center" width="120" />
          <el-table-column label="单位" prop="unit" align="center" width="80" />
          <el-table-column label="计划数量" prop="qtyNum" align="center" width="100" />
          <el-table-column label="实际生产数量" prop="actualQty" align="center" width="120" />
          <el-table-column label="需求日期" prop="requiredDate" align="center" width="120" />
          <el-table-column label="计划开工时间" prop="planStartTime" align="center" width="120" />
          <el-table-column label="计划完工时间" prop="planEndTime" align="center" width="120" />
          <el-table-column label="实际开工时间" prop="actualStartTime" align="center" width="120" />
          <el-table-column label="实际完工时间" prop="actualEndTime" align="center" width="120" />
          <el-table-column label="状态" prop="status" align="center" width="100" fixed="right">
          <template slot-scope="scope">
              <el-tag :type="scope.row.statusType">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
          <el-table-column label="操作" align="center" width="120" fixed="right">
          <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleViewWorkOrder(scope.row)">查看</el-button>
              <el-button v-if="scope.row.status === '待排产' || scope.row.status === '未开始'" size="mini" type="text" @click="handleArrangeProd(scope.row)">排产</el-button>
          </template>
        </el-table-column>
      </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>

      <el-tab-pane label="BOM组成" name="bomComposition">
        <div class="table-toolbar">
          <el-button size="small" type="primary" plain icon="el-icon-download">导出</el-button>
        </div>
        <div class="bom-info">
          <span>BOM编号：{{ bomInfo.bomCode }}</span>
          <span>BOM版本：{{ bomInfo.bomVersion }}</span>
        </div>
        <el-table :data="bomList" style="width: 100%">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="产品名称" prop="productName" align="center" />
          <el-table-column label="产品编号" prop="productCode" align="center" />
          <el-table-column label="规格型号" prop="specifications" align="center" />
          <el-table-column label="单位" prop="unit" align="center" />
          <el-table-column label="BOM编号" prop="bomCode" align="center" />
          <el-table-column label="BOM版本" prop="bomVersion" align="center" />
          <el-table-column label="使用量" prop="materialUsage" align="center" />
          <el-table-column label="使用比例" prop="usageRatio" align="center" />
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="生产产品" name="productionProducts">
        <div class="table-toolbar">
          <el-button size="small" type="primary" plain icon="el-icon-download">导出</el-button>
        </div>
        <el-table :data="productList" style="width: 100%">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="产品编号" prop="productCode" align="center" />
          <el-table-column label="产品名称" prop="productName" align="center" />
          <el-table-column label="规格型号" prop="specifications" align="center" />
          <el-table-column label="单位" prop="unit" align="center" />
          <el-table-column label="产品类型" prop="productType" align="center" />
          <el-table-column label="计划生产数量" prop="plannedQty" align="center" />
          <el-table-column label="实际生产数量" prop="actualQty" align="center" />
        </el-table>
        <div class="total-info">
          <span>计划总数量：{{ totalPlanned }}</span>
          <span>实际总数量：{{ totalActual }}</span>
        </div>
      </el-tab-pane>

      <el-tab-pane label="物料明细" name="materialDetails">
        <div class="table-toolbar">
          <el-button size="small" type="primary" plain icon="el-icon-download">导出</el-button>
        </div>
        <el-table :data="materialList" style="width: 100%">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="物料编号" prop="materialCode" align="center" />
          <el-table-column label="物料名称" prop="materialName" align="center" />
          <el-table-column label="规格型号" prop="specification" align="center" />
          <el-table-column label="单位" prop="unit" align="center" />
          <el-table-column label="物料类型" prop="materialType" align="center" />
          <el-table-column label="预计使用量" prop="estimatedUsage" align="center" />
          <el-table-column label="实际使用量" prop="actualUsage" align="center" />
        </el-table>
        <div class="total-info">
          <span>预计使用总量：{{ totalEstimated }}</span>
          <span>实际使用总量：{{ totalActualUsage }}</span>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="action-footer">
      <el-button @click="goBack">关闭</el-button>
    </div>
  </div>
</template>

<script>
// 导入正确的API函数
import { getProductionPlan, getProductListByPlanCode, getMaterialListByPlanCode } from "@/api/sc/productionPlan";
import { decomposePlan, getWorkOrdersByPlan, getBomByPlanCode } from "@/api/sc/plan";
import DictTag from "@/components/DictTag";
import Pagination from "@/components/Pagination";

export default {
  name: "DetailPlan",
  dicts: ['product_type'],
  components: {
    DictTag,
    Pagination
  },
  data() {
    return {
      activeTab: 'baseInfo',
      // 加载状态
      loading: false,
      // 生产计划信息
      planInfo: {
        planCode: "",
        planName: "",
        sourceType: "",
        orderCode: "",
        creator: "",
        createTime: "",
        status: "",
        planStartTime: "",
        planEndTime: "",
        requiredDate: "",
        remark: "",
        productCode: "",
        productName: "",
        specification: "",
        unit: "",
        productType: "",
        plannedQty: 0,
        attachment: null
      },
      // 工单列表
      workOrderList: [
        {
          workOrderCode: "GD0235",
          workOrderName: "新产品工单",
          progress: "30%",
          progressValue: 30,
          progressColor: "#409EFF",
          relatedPlan: "新产品计划",
          productName: "新产品02",
          productCode: "CP02",
          specification: "RED",
          unit: "个",
          plannedQty: 100,
          actualQty: 30,
          requiredDate: "2023-07-02",
          planStartTime: "2023-04-19",
          planEndTime: "2023-06-19",
          actualStartTime: "2023-04-20",
          actualEndTime: "",
          status: "进行中",
          statusType: "primary",
        },
        {
          workOrderCode: "GD0236",
          workOrderName: "新产品工单",
          progress: "0%",
          progressValue: 0,
          progressColor: "#909399",
          relatedPlan: "新产品计划",
          productName: "新产品02",
          productCode: "CP02",
          specification: "BLUE",
          unit: "个",
          plannedQty: 50,
          actualQty: 0,
          requiredDate: "2023-07-02",
          planStartTime: "2023-06-20",
          planEndTime: "2023-06-30",
          actualStartTime: "",
          actualEndTime: "",
          status: "未开始",
          statusType: "info",
        }
      ],
      // BOM信息
      bomInfo: {
        bomCode: "BOM00003",
        bomVersion: "1.3"
      },
      // BOM列表
      bomList: [
        {
          productName: "产品一",
          productCode: "WL025",
          specification: "蓝色",
          unit: "个",
          bomCode: "BOM00001",
          bomVersion: "1.0",
          quantity: 50,
          usageRatio: "20%"
        },
        {
          productName: "产品二",
          productCode: "WL025",
          specification: "蓝色",
          unit: "个",
          bomCode: "BOM00002",
          bomVersion: "1.2",
          quantity: 50,
          usageRatio: "20%"
        },
        {
          productName: "产品三",
          productCode: "WL025",
          specification: "蓝色",
          unit: "个",
          bomCode: "BOM00003",
          bomVersion: "1.2",
          quantity: 50,
          usageRatio: "20%"
        },
        {
          productName: "物料四",
          productCode: "WL025",
          specification: "蓝色",
          unit: "个",
          bomCode: "",
          bomVersion: "",
          quantity: 50,
          usageRatio: "20%"
        }
      ],
      // 产品列表
      productList: [
        {
          productCode: "CPBH0235",
          productName: "产品一",
          specification: "红色",
          unit: "个",
          productType: "半成品",
          plannedQty: 20,
          actualQty: 10
        },
        {
          productCode: "CPBH0235",
          productName: "产品一",
          specification: "红色",
          unit: "个",
          productType: "半成品",
          plannedQty: 20,
          actualQty: 10
        },
        {
          productCode: "CPBH0235",
          productName: "产品一",
          specification: "红色",
          unit: "个",
          productType: "半成品",
          plannedQty: 20,
          actualQty: 10
        }
      ],
      // 物料列表
      materialList: [
        {
          materialCode: "WLBH0235",
          materialName: "物料一",
          specification: "500*500*600",
          unit: "kg",
          materialType: "生产原材料",
          estimatedUsage: 100,
          actualUsage: 0
        },
        {
          materialCode: "WLBH0235",
          materialName: "物料一",
          specification: "500*500*600",
          unit: "kg",
          materialType: "生产原材料",
          estimatedUsage: 100,
          actualUsage: 0
        },
        {
          materialCode: "WLBH0235",
          materialName: "物料一",
          specification: "500*500*600",
          unit: "kg",
          materialType: "生产原材料",
          estimatedUsage: 100,
          actualUsage: 0
        }
      ],
      // 分页参数
      total: 10,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 汇总计算
      totalPlanned: 90,
      totalActual: 90,
      totalEstimated: 90,
      totalActualUsage: 90,
      // 状态信息
      statusInfo: { text: '未知状态', type: 'info' }
    };
  },
  created() {
    const planCode = this.$route.query.planCode;
    if (planCode) {
      this.getPlanDetail(planCode);
    }
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/plan/detail' || to.name === 'DetailPlan') {
        console.log('计划详情页面路由变化，刷新数据');
        const planCode = to.query.planCode;
        if (planCode) {
          this.getPlanDetail(planCode);
        }
      }
    }
  },
  methods: {
    // 获取计划详情
    getPlanDetail(planCode) {
      this.loading = true;
      // 调用API获取生产计划详情
      getProductionPlan(planCode).then(response => {
        if (response.code === 200) {
          // 更新基础信息
          const planData = response.data || {};
          
          // 格式化日期
          if (planData.planStartTime) {
            planData.planStartTime = this.parseTime(planData.planStartTime, '{y}-{m}-{d}');
          }
          if (planData.planEndTime) {
            planData.planEndTime = this.parseTime(planData.planEndTime, '{y}-{m}-{d}');
          }
          if (planData.requiredDate) {
            planData.requiredDate = this.parseTime(planData.requiredDate, '{y}-{m}-{d}');
          }
          
          // 设置状态标签样式
          this.setStatusStyle(planData.status);
          
          // 更新计划信息
          this.planInfo = {
            ...this.planInfo,
            ...planData,
            // 确保creator和createTime正确映射
            creator: planData.createBy || this.planInfo.creator,
            createTime: this.parseTime(planData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') || this.planInfo.createTime
          };
          
          // 获取工单列表
          this.getWorkOrderList(planCode);
          
          // 获取BOM信息
          this.getBomInfo(planCode);
          
          // 获取产品列表
          this.getProductList(planCode);
          
          // 获取物料列表
          this.getMaterialList(planCode);
        } else {
          this.$message.error(response.msg || '获取计划详情失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取计划详情失败:", error);
        this.loading = false;
        this.$message.error('获取计划详情失败，请稍后重试');
        
        // 开发环境下使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          console.log("使用模拟数据展示界面");
          
          // 设置示例数据用于开发测试
          this.planInfo = {
            planCode: "SCJH-20240730-001",
            planName: "新产品生产计划0545",
            sourceType: "销售订单",
            orderCode: "DDBH02154",
            creator: "李小海",
            createTime: "2025-07-01 19:15:00",
            status: "1", // 已分解
            planStartTime: "2023-04-19",
            planEndTime: "2023-06-19",
            requiredDate: "2023-07-02",
            remark: "",
            productCode: "CPBH035345",
            productName: "新产品一",
            specification: "RED",
            unit: "个",
            productType: "成品",
            plannedQty: 150,
            attachment: null
          };
          
          // 设置状态标签
          this.setStatusStyle(this.planInfo.status);
        }
      });
    },
    
    // 设置状态标签样式
    setStatusStyle(status) {
      // 根据状态值设置样式
      const statusMap = {
        '0': { text: '未分解', type: 'warning' },
        '1': { text: '已分解', type: 'success' },
        '2': { text: '进行中', type: 'primary' },
        '3': { text: '已完成', type: 'info' },
        '4': { text: '已关闭', type: 'danger' },
        '5': { text: '已撤回', type: 'info' }
      };
      
      const statusInfo = statusMap[status] || { text: '未知状态', type: 'info' };
      this.statusInfo = statusInfo;
    },
    
    // 获取工单列表
    getWorkOrderList(planCode) {
      getWorkOrdersByPlan(planCode).then(response => {
        const workOrders = response.rows || [];
        // 处理工单进度数据
        workOrders.forEach(item => {
          // 确保progressValue是数字
          if (item.completedQty && item.plannedQty > 0) {
            item.progressValue = Math.round((item.completedQty / item.plannedQty) * 100);
          } else {
            item.progressValue = 0;
          }
        });
        this.workOrderList = workOrders;
      });
    },
    
    // 获取BOM信息
    getBomInfo(planCode) {
      if (!planCode) return;
      getBomByPlanCode(planCode).then(response => {
        if (response.code === 200 && response.data) {
          const bomData = response.data;
          this.bomInfo.bomCode = bomData.bomCode;
          this.bomInfo.bomVersion = bomData.bomVersion; // 假设VO中有bomVersion
          this.bomList = bomData.details || [];
        } else {
          // 清空或显示未找到BOM的提示
          this.bomInfo = { bomCode: null, bomVersion: null };
          this.bomList = [];
        }
      }).catch(error => {
        console.error("获取BOM信息失败:", error);
        this.bomInfo = { bomCode: null, bomVersion: null };
        this.bomList = [];
      });
    },
    
    // 获取产品列表
    getProductList(planCode) {
      this.totalPlanned = 0;
      this.totalActual = 0;
      getProductListByPlanCode(planCode).then(response => {
        if (response.code === 200) {
          this.productList = response.data || [];
          // 计算总数
          this.calculateProductTotal();
        } else {
          this.productList = [];
        }
      });
    },
    
    // 获取物料列表
    getMaterialList(planCode) {
      this.totalEstimated = 0;
      this.totalActualUsage = 0;
      getMaterialListByPlanCode(planCode).then(response => {
        if (response.code === 200) {
          this.materialList = response.data || [];
          this.calculateMaterialTotal();
        } else {
          this.materialList = [];
        }
      });
    },
    
    // 计算产品总数
    calculateProductTotal() {
      this.totalPlanned = this.productList.reduce((sum, item) => sum + (Number(item.plannedQty) || 0), 0);
      this.totalActual = this.productList.reduce((sum, item) => sum + (Number(item.actualQty) || 0), 0);
    },
    
    // 计算物料总数
    calculateMaterialTotal() {
      this.totalEstimated = this.materialList.reduce((sum, item) => sum + (Number(item.estimatedUsage) || 0), 0);
      this.totalActualUsage = this.materialList.reduce((sum, item) => sum + (Number(item.actualUsage) || 0), 0);
    },
    
    // 日期格式化
    parseTime(time, pattern) {
      if (time == null || time === '') {
        return "";
      }
      const format = pattern || '{y}-{m}-{d}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        if (result.length > 0 && value < 10) {
          value = '0' + value;
        }
        return value || 0;
      });
      return time_str;
    },
    
    // 返回按钮
    goBack() {
      this.$router.push({ path: '/sc/plan' });
    },
    // 编辑按钮
    handleEdit() {
      this.$router.push({ path: '/sc/plan/edit', query: { planCode: this.planInfo.planCode } });
    },
    // 删除按钮
    handleDelete() {
      this.$modal.confirm('是否确认删除该生产计划？').then(() => {
        this.$message.success("删除成功");
        this.goBack();
      }).catch(() => {});
    },
    // 分解按钮
    handleSplit() {
      this.$modal.confirm('是否确认分解该生产计划？').then(() => {
        this.loading = true;
        decomposePlan(this.planInfo.planCode).then(response => {
          this.loading = false;
          if (response.code === 200) {
            this.$modal.msgSuccess("分解成功");
            // 重新加载计划信息
            this.getPlanDetail(this.planInfo.planCode);
          } else {
            this.$modal.msgError(response.msg || "分解失败");
          }
        }).catch(error => {
          this.loading = false;
          console.error("分解生产计划失败:", error);
          this.$modal.msgError("分解失败，请稍后重试");
        });
      }).catch(() => {});
    },
    // 打印按钮
    handlePrint() {
      this.$message.success("打印功能待实现");
    },
    // 查看工单
    handleViewWorkOrder(row) {
      this.$router.push({ path: '/sc/work/detail', query: { workOrderCode: row.workOrderCode } });
    },
    // 排产
    handleArrangeProd(row) {
      this.$router.push({ path: '/sc/work/arrange', query: { workOrderCode: row.workOrderCode } });
    },
    // 获取列表
    getList() {
      // 模拟分页效果
      this.$message.success(`加载第${this.queryParams.pageNum}页数据`);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  margin-right: 10px;
  font-size: 18px;
}

.creator-info {
  display: flex;
  flex-direction: column;
  font-size: 14px;
}

.status-tag {
  display: flex;
  align-items: center;
}

.tag-wrapper {
  border-radius: 20px;
  padding: 5px 15px;
}

/* 状态标签样式 */
.status-warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-primary {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-success {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-info {
  background-color: #f4f4f5;
  color: #909399;
}

.status-danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.action-bar {
  display: flex;
  margin-bottom: 20px;
}

.action-bar .el-button {
  margin-right: 10px;
}

.table-toolbar {
  margin-bottom: 15px;
  text-align: right;
}

.bom-info {
  display: flex;
  margin-bottom: 15px;
  font-size: 14px;
}

.bom-info span {
  margin-right: 20px;
}

.total-info {
  margin-top: 15px;
  text-align: right;
  font-weight: bold;
}

.total-info span {
  margin-left: 20px;
}

.action-footer {
  margin-top: 20px;
  text-align: center;
}

/* Tab样式优化 */
::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

::v-deep .el-tabs__content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格样式优化 */
::v-deep .el-table th {
  background-color: #f5f7fa;
}
</style>
